package com.bluesky.plum.domain.repository.impl;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.beanutils.PropertyUtils;

import com.bluesky.plum.domain.Person;
import com.bluesky.plum.domain.repository.BaseRepository;
import com.bluesky.plum.domain.repository.Repository;
import com.bluesky.plum.domain.repository.search.condition.Condition;

/**
 * wrap a List to a Repository
 * 
 * @author jack
 * 
 * @param <T>
 */
public class ListRepository<T> extends BaseRepository<T> implements Repository<T> {
	protected List<T> list;

	public ListRepository(List<T> list) {
		this.list = list;

	}

	@Override
	public synchronized void add(T entity) {
		list.add(entity);
	}

	@Override
	public synchronized void remove(T entity) {

		list.remove(entity);
	}

	@Override
	public synchronized List<T> getAll() {

		return list;
	}

	@Override
	public synchronized T getByIndex(int index) {

		return list.get(index);
	}

	@Override
	public synchronized List<T> getByPage(int pageLength, int pageNumber) {
		List<T> rslt = new ArrayList<T>();

		int start = pageLength * pageNumber;
		if (start >= getCount())
			throw new RuntimeException("the page do not exist");

		int end = start + pageLength;
		if (end >= list.size())
			end = list.size();

		for (int i = start; i < end; i++)
			rslt.add(list.get(i));

		return rslt;
	}

	@Override
	public synchronized int getCount() {

		return list.size();
	}

	@Override
	public synchronized void update(T oldEntity, T newEntity) {
		// copy object
		//FieldUtil2.copyFields(newEntity, oldEntity);
		try {
			PropertyUtils.copyProperties(newEntity, oldEntity);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			throw new RuntimeException(e);
		}

	}

	@Override
	public List<T> find(Condition condition) {
		// TODO Auto-generated method stub
		return null;
	}

	
	
}
